//
//  QYGRechargeView.m
//  wawaji_ios
//
//  Created by 云+物娱 on 2017/12/1.
//  Copyright © 2017年 yiguo qi. All rights reserved.
//

#import "QYGRechargeView.h"
#import "QYGRechargeCell.h"
#import "QYGCoinRecordModel.h"
#import "QYGNetRequestModel.h"
#import "QYGPaymentModel.h"


static NSString *rechargeIdentifier = @"rechargeIdentifier";

@interface QYGRechargeView()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) QYGCoinListModel *coinListModel;
@property (nonatomic, assign) NSInteger currentPayId;
@property (strong, nonatomic) NSTimer *requestTimer;
@property (nonatomic, assign) NSInteger requestCount;

@end

@implementation QYGRechargeView


- (instancetype)initWithFrame:(CGRect)frame
{
    if(self = [super initWithFrame:frame])
    {
        self.backgroundColor = [UIColor whiteColor];
        [self setupUI];
    }
    return self;
}

#pragma mark - tableViewDelegate
- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.coinListArr.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return ScaleW(82.5);
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.1f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.1f;
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    return  nil;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return  nil;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    QYGRechargeCell *cell = [tableView dequeueReusableCellWithIdentifier:rechargeIdentifier forIndexPath:indexPath];
    cell.item = indexPath.row;
    cell.coinListModel = self.coinListArr[indexPath.row];
    WS(weakSelf);
    [cell setSureBlock:^(NSInteger item) {
        [weakSelf requestPayWithItem:item];
        
    }];
    return cell;
}

#pragma mark - setupUI
- (void)setupUI
{
    [self viewWithcornerRadius:10 borderWidth:0 borderColor:nil backgroundColor:[UIColor colorWithHex:@"ffb52b"]];
    
    [self addSubview:self.titleLabel];
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.mas_top);
        make.left.equalTo(self.mas_left);
        make.right.equalTo(self.mas_right);
        make.height.equalTo(@(ScaleW(55)));
    }];
    
    
    [self addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.titleLabel.mas_bottom);
        make.left.mas_equalTo(ScaleW(15));
        make.right.mas_equalTo(-ScaleW(15));
        make.bottom.equalTo(self.mas_bottom).offset(-ScaleW(15));
    }];
    
//    [self addSubview:self.cancelBtn];
//    [self.cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.equalTo(self.mas_left);
//        make.right.equalTo(self.mas_right);
//        make.bottom.equalTo(self.mas_bottom);
//        make.height.equalTo(@(ScaleW(44)));
//
//    }];
    
//    UIView *line = [SGUtil newViewWithBgColor:[UIColor cm_backgroudColor]];
//    [self addSubview:line];
//    [line mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(self.titleLabel.mas_bottom).offset(-0.5);
//        make.left.equalTo(self.titleLabel.mas_left).offset(10);
//        make.right.equalTo(self.titleLabel.mas_right).offset(-10);
//        make.height.equalTo(@0.5);
//    }];
    
}

#pragma mark - target
- (void)cancelBtnBtnClicked
{
    if(self.closeBlock)
    {
        self.closeBlock();
    }
}


#pragma mark - 内部方法


- (void)requestPayWithItem:(NSInteger)item{
    
    if(![SGUtil WXAppIsInstalled]) return;
    KeyWindow.userInteractionEnabled = NO;
   // 请求支付
    [SVProgressHUD show];
    self.coinListModel = self.coinListArr[item];
    //生成支付交易单号
    [QYGNetRequestModel postPaymentWithCoin_id:self.coinListModel.coinId completed:^(QYGPaymentModel *paymentModel) {
        
        self.currentPayId = paymentModel.pay_id;
        if(![QYGKeychain payType]){
            // 获取支付参数配置
            [QYGNetRequestModel getPayParamsWithPay_id:paymentModel.pay_id completed:^(QYGPreparamModel *prePaymentModel) {
                [SGUtil shareUtil].coinListModel = self.coinListArr[item];
                [SGUtil shareUtil].pay_id = paymentModel.pay_id;
                
                // 调微信支付
                [SGUtil WXPayWithOpenId:nil partnerId:prePaymentModel.partnerid prepayId:prePaymentModel.prepayid package:prePaymentModel.package nonceStr:prePaymentModel.noncestr stamp:prePaymentModel.timestamp sign:prePaymentModel.sign];
                KeyWindow.userInteractionEnabled = YES;
                [self cancelBtnBtnClicked];
            } WithErrorCodeBlock:^(NSError *error) {
                KeyWindow.userInteractionEnabled = YES;
            }];
        }else{
           
            self.requestTimer = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(requestAction) userInfo:nil repeats:YES];
        }
        
    } WithErrorCodeBlock:^(NSError *error) {
        
        KeyWindow.userInteractionEnabled = YES;
    }];
    
}
- (void)requestAction{
    
    self.requestCount += 1;
    
    [QYGNetRequestModel getCheckPaymentWithPay_id:self.currentPayId completed:^(QYGPaymentModel *paymentModel) {
        
        if( [paymentModel.status isEqualToString:@"paid"]){
            [self showPayResult:YES];
            
        }else{
            if(self.requestCount >5){
                // 支付失败
                [self showPayResult:NO];
            }
        }
    } WithErrorCodeBlock:^(NSError *error) {
        
        if(self.requestCount >5){
            // 支付失败
            [self showPayResult:NO];
        }
    }];
}

- (void)showPayResult:(BOOL)isSuccess{
    //
    KeyWindow.userInteractionEnabled = YES;
    [SVProgressHUD dismiss];
    [self.requestTimer invalidate];
    self.requestTimer = nil;
    self.requestCount = 0;
    
    if(self.rechargeBlock){
        self.rechargeBlock(isSuccess, self.coinListModel);
        
    }
}


- (void)setCoinListArr:(NSArray *)coinListArr{
    _coinListArr = coinListArr;
    [self.tableView reloadData];
}


#pragma mark lazy

- (UILabel *)titleLabel
{
    if(!_titleLabel)
    {
        _titleLabel = [SGUtil newLabelWithFont:ScaleBoldFont(15) textColor:[UIColor colorWithHex:@"ffffff"] text:@"充娃娃币"];
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        
    }
    return _titleLabel;
}

- (UITableView *)tableView
{
    if(!_tableView)
    {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView viewWithcornerRadius:8 borderWidth:0 borderColor:nil backgroundColor:[UIColor whiteColor]];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        [_tableView registerClass:[QYGRechargeCell class] forCellReuseIdentifier:rechargeIdentifier];
    }
    return _tableView;
}

//- (UIButton *)cancelBtn
//{
//    if(!_cancelBtn)
//    {
//        _cancelBtn = [SGUtil newButtonWithTitleFont:ScaleBoldFont(14) title:@"取消" titleColor:[UIColor colorWithHex:@"555555"]];
//        [_cancelBtn addTarget:self action:@selector(cancelBtnBtnClicked) forControlEvents:UIControlEventTouchUpInside];
//    }
//    return _cancelBtn;
//}
@end
